/**
 * @Project： Lqyd_Android
 * @Title：QyReaderApp
 * @Description：
 * @Author：wayne
 * @Date：2014年8月7日下午11:53:22
 */
package com.shwread.android.qysw;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.os.Environment;

import com.ciko.code.bean.UserBean;
import com.mywork.WorkUIKit;
import com.netease.nim.demo.NimCache;
import com.netease.nim.demo.main.activity.NimAVChatActivity;
import com.netease.nim.demo.session.SessionManager;
import com.netease.nim.demo.util.SystemUtil;
import com.netease.nim.demo.util.storage.StorageUtil;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.SDKOptions;
import com.netease.nimlib.sdk.StatusBarNotificationConfig;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.avchat.AVChatManager;
import com.netease.nimlib.sdk.avchat.model.AVChatData;
import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw.step.model.UserHealthyDataModel;
import com.shwread.android.qysw10000152.R;
import com.shwread.http.ActionHelp;
import com.shwread.http.TrainActionHelp;
import com.shwread.http.util.HttpResponseConfig;
import com.shwread.httpsdk.util.NetUtil;

import net.nightwhistler.htmlspanner.FontFamily;
import net.nightwhistler.pageturner.Configuration;

import org.geometerplus.zlibrary.ui.android.library.ZLAndroidApplication;

import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.constants.NoFormateConsts;
import logic.dao.UserDao;
import logic.util.AppUtils;
import logic.util.ImageLoaderUtil;
import logic.util.SDcardUtil;
import logic.util.ScreenUtil;
import logic.util.logutil.LogUtil;


/**
 * @Project： Lqyd_Android
 * @Title：QyReaderApp
 * @Description：
 * @Author：wayne
 * @Date：2014年8月7日下午11:53:22
 */
public class QyReaderApp
        extends
        ZLAndroidApplication
{

	public static QyReaderApp application;

	public static QyReaderApp getApplication() {
		return application;
	}
	@Override
	public void onCreate() {
		super.onCreate();
		application = this;
		//sd卡初始化
		SDcardUtil.init();
//		MultiDex.install(this);
		WorkUIKit.init(this);
		UserHealthyDataModel.getInstance().init();
		//初始化日志类
		LogUtil.isApplicationDebug(this);
		LogUtil.onError(this);
		ImageLoaderUtil.initImageLoader(this, null);

		//初始化屏幕数据
		ScreenUtil.GetInfo(this);

		//初始化云信相关数据
		StorageUtil.init(this, null);
		NimCache.setContext(this);
		NIMClient.init(this, getLoginInfo(), getOptions());

		HttpResponseConfig.CONTEXT = this;
		HttpResponseConfig.EXCEPTION_LOGIN_CODE = DefaultConsts.EXCEPTION_LOGIN_CODE;
		HttpResponseConfig.EXCEPTION_LOGIN_STRING = DefaultConsts.EXCEPTION_LOGIN_STRING;
		HttpResponseConfig.PARAMS_EMPTY_CODE = DefaultConsts.PARAMS_EMPTY_CODE;
		HttpResponseConfig.PARAMS_EMPTY_STRING = DefaultConsts.PARAMS_EMPTY_STRING;
		HttpResponseConfig.PACKAGE_NAME = AppUtils.getPackageName(this);
		ActionHelp.init(NetUtil.getImei(this), NetUtil.getPsdnIp(), Const.SERVER_URL.equals("http://42.121.255.69:8080/hzlqswserver"));
		ActionHelp.setEnterpriseId(NoFormateConsts.enterprise_num);
		ActionHelp.setClientType(Const.CLIENTTYPE);
		ActionHelp.initLion(true);
		TrainActionHelp.init(NetUtil.getImei(this), NetUtil.getPsdnIp(), Const.TRAIN_URL.equals("http://42.121.253.209:8081/lqsw_website/"));
		TrainActionHelp.setEnterpriseId(NoFormateConsts.enterprise_num);
		TrainActionHelp.setClientType(Const.CLIENTTYPE);
		
		//		// 在IntentFilter中选择你要监听的行为  
		IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);// sd卡被插入，且已经挂载  
		intentFilter.setPriority(1000);// 设置最高优先级  
		registerReceiver(new SDBroadcastReceiver(), intentFilter);// 注册监听函数 
		
		if (inMainProcess())
		{
			// init pinyin
			//            PinYin.init(this);
			//            PinYin.validate();

			// 开启/关闭通知栏消息提醒
			NIMClient.toggleNotification(true);
			SessionManager.init();
			enableAVChat();
		}

		initFontfamily();
	}

	private void enableAVChat() {
		registerAVChatIncomingCallObserver(true);
	}

	private void registerAVChatIncomingCallObserver(boolean register) {
		AVChatManager.getInstance().observeIncomingCall(new Observer<AVChatData>() {
			@Override
			public void onEvent(AVChatData chatData) {
				String account;
				UserBean user = UserDao.getInstance(getApplicationContext()).getLastLoginUser();
				if (user == null)
				{
					account = NimCache.getAccount();
				}
				else
				{
					account = user.getImAccount();
				}
				NimAVChatActivity.launch(getApplicationContext(), account, chatData.getAccount(), chatData.getChatType().getValue(), false);
			}
		}, register);
	}
	
	public static class SDBroadcastReceiver
	        extends
	        BroadcastReceiver
	{
		
		public SDBroadcastReceiver() {
		}
		
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals("android.intent.action.MEDIA_MOUNTED"))// SD  
			// 卡已经成功挂载  
			{
				SDcardUtil.init();
			}
		}
		
	}
	
	private SDKOptions getOptions() {
		SDKOptions options = new SDKOptions();
		
		// 如果将新消息通知提醒托管给SDK完成，需要添加以下配置。
		// 其中notificationSmallIconId必须提供
		StatusBarNotificationConfig config = new StatusBarNotificationConfig();
		config.notificationEntrance = MainActivity.class;
		config.notificationSmallIconId = R.drawable.ic_launcher;
		options.statusBarNotificationConfig = config;
		NimCache.setConfig(config);
		
		// 配置保存图片，文件，log等数据的目录
		String sdkPath = Environment.getExternalStorageDirectory() + "/" + getPackageName() + "/nim";
		options.sdkStorageRootPath = sdkPath;
		
		// 配置数据库加密秘钥
		options.databaseEncryptKey = "NETEASE";
		
		// 配置是否需要预下载附件缩略图
		options.preloadAttach = true;
		
		// 配置附件缩略图的尺寸大小，
		options.thumbnailSize = ScreenUtil.screenMin / 2;
		
		return options;
	}
	
	private LoginInfo getLoginInfo() {
		//        String account = Preferences.getUserAccount();
		//        String token = Preferences.getUserToken();
		//
		//        if (!TextUtils.isEmpty(account) && !TextUtils.isEmpty(token)) {
		//            DemoCache.setAccount(account);
		//            // open db
		//            DatabaseManager.getInstance().open(this);
		//            return new LoginInfo(account, token);
		//        } else {
		return null;
		//        }
	}
	
	public boolean inMainProcess() {
		String packageName = getPackageName();
		String processName = SystemUtil.getProcessName(this);
		return packageName.equals(processName);
	}
	
	private static FontFamily kaiFontFamily;
	public static FontFamily getFontFamily() {
		return kaiFontFamily;
	}
	
	private void initFontfamily(){
		new Thread(new Runnable()
		{
			@Override
			public void run() {
				Typeface basic = Typeface.createFromAsset(getAssets(), "fonts/" + Configuration.CN_FONT_KAITI + ".ttf");
				kaiFontFamily = new FontFamily(Configuration.CN_FONT_KAITI, basic);
			}
		}).start();
	}
}
